package com.example.loginmvvm.player

import com.example.loginmvvm.player.domain.Music

/*
 * class title: 
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2021/4/19.
 * PS: Not easy to write code, please indicate.
 */

/**
 * 播放音乐
 * 暂停音乐
 * 上一首
 * 下一首
 * ========================
 * 播放的状态：
 * -通知ui改变播放状态
 * -通知ui进度的变化
 * 上一首，下一首
 * -通知ui歌曲标题的变化
 * -通知ui歌曲封面变换
 * 暂停音乐
 * -更新ui状态为暂停
 *
 * 相关数据：
 * 当前播放的歌曲
 * 当前播放的状态
 */

/**
 * 单例PlayerPresenter类
 * 1.先私有化构造方法
 * 2.写一个伴随类，相当一java的静态对象
 * by lazy{} 是懒加载，需要的时候在加载，而且不会重复加载，并且是线程安全的
 * 这样创建的才是同一个对象
 * ui驱动开发
 */
class PlayerPresenter private constructor() {

    private val playerModel by lazy {
        PlayerModel()
    }

    private val player by lazy {
        MusicPlayer()
    }

    companion object {
        val instance by lazy {
            PlayerPresenter()
        }
    }

    enum class PlayState {
        NONE, PLAYING, PAUSE, LOADING
    }

    var currentMusic = DataListenContainer<Music>()

    //private lateinit var currentMusic: Music
    var currentPlayState = DataListenContainer<PlayState>()
    private val livePlayerState = LivePlayerState.instance

    /**
     * 根据状态控制音乐 播放是暂停
     */
    fun doPlayOrPause() {
        if (currentMusic.value == null) {
            currentMusic.value = playerModel.getMusicById("卡农")
        }
        player.play(currentMusic.value)

        if (currentPlayState.value != PlayState.PLAYING) {
            //开始播放音乐
            currentPlayState.value = PlayState.PLAYING

            livePlayerState.postValue(PlayState.PLAYING)
        } else {
            //暂停播放
            currentPlayState.value = PlayState.PAUSE

            livePlayerState.postValue(PlayState.PAUSE)
        }
    }

    /**
     * 播放下一首歌曲
     */
    fun playNext() {
        currentMusic.value = playerModel.getMusicById("下一首：梦中的婚礼")
        //1.拿到下一首歌曲-->变更ui，包括标题和封面
        //2.设置给播放器
        //3.等待播放器的回调通知

        currentPlayState.value = PlayState.PLAYING
    }

    /**
     * 播放上一首歌曲
     */
    fun playPre() {
        currentMusic.value = playerModel.getMusicById("上一首：圣母颂")
        currentPlayState.value = PlayState.PLAYING
    }
}